package dog.weatherwallpaper;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import dog.weatherwallpaper.model.AbstractWeather;
import dog.weatherwallpaper.model.Unit;
import dog.weatherwallpaper.model.Weather;
import dog.weatherwallpaper.model.WeatherInfo;
import dog.weatherwallpaper.utils.App;
import dog.weatherwallpaper.utils.Internet;

public final class MainActivity extends FragmentActivity {
	public static final String RELOAD = "reload";
	private SharedPreferences sp;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.main);

		PreferenceManager.setDefaultValues(this, R.xml.settings, false);
		sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

		if (new Internet().isConnected()) {
			if (WeatherInfo.getInstance().isOldWeather(1)) {
				new UpdateTask().execute();
			} else if (App.getConnectivityManager().getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
				new CheckVersionTask(this).execute();
			}
		}
		LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(receiver, new IntentFilter(RELOAD));
	}

	private BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			finish();
			startActivity(getIntent());
		}
	};

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.getMenuInflater().inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.settings:
			settings();
			return true;
		case R.id.help:
			help();
			return true;
		case R.id.about:
			about();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		updateTextAndIcons();
	}

	private void updateTextAndIcons() {
		TextView text = (TextView) findViewById(R.id.location);
		text.setText(WeatherInfo.getInstance().getLocation().get());

		updateEachTextAndIcon(R.id.current, 0);
		updateEachTextAndIcon(R.id.dayOne, 1);
		updateEachTextAndIcon(R.id.dayTwo, 2);
		updateEachTextAndIcon(R.id.dayThree, 3);
		updateEachTextAndIcon(R.id.dayFour, 4);
		updateEachTextAndIcon(R.id.dayFive, 5);
	}

	private void updateEachTextAndIcon(final int textId, final int day) {
		boolean celsius = sp.getBoolean(getString(R.string.temperature_key), true);
		boolean km = sp.getBoolean(getString(R.string.distance_key), true);
		Unit unit = new Unit(celsius, km);

		Weather weather = WeatherInfo.getInstance().getWeather();
		AbstractWeather aw = day == 0 ? weather.getCurrent() : weather.getDay(day - 1);

		TextView text = (TextView) findViewById(textId);
		text.setVisibility(View.VISIBLE);
		text.setText(aw.getAllInfo(unit));
		int iconID = App.getIconId(aw.getIconName());
		text.setCompoundDrawablesWithIntrinsicBounds(iconID, 0, 0, 0);
	}

	private void settings() {
		App.startActivity(SettingsActivity.class);
	}

	private void help() {
		App.startActivity(HelpActivity.class);
	}

	private void about() {
		App.startActivity(AboutActivity.class);
	}

	private class UpdateTask extends AsyncTask<Void, Void, Boolean> {
		@Override
		protected void onPreExecute() {
			App.toast(R.string.getting_weather_info, Toast.LENGTH_SHORT);
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			return WeatherInfo.getInstance().update();
		}

		@Override
		protected void onPostExecute(Boolean updated) {
			if (updated) {
				updateTextAndIcons();
				App.toast(R.string.weather_info_updated, Toast.LENGTH_SHORT);
			} else {
				App.toast(R.string.update_failed, Toast.LENGTH_LONG);
			}
		}
	}

	private class CheckVersionTask extends AsyncTask<String, Integer, Integer> {
		private Context context;

		public CheckVersionTask(Context context) {
			this.context = context;
		}

		@Override
		protected void onPreExecute() {
			App.toast(R.string.checking_version, Toast.LENGTH_SHORT);
		}

		@Override
		protected Integer doInBackground(String... params) {
			return new Internet().getVersion();
		}

		@Override
		protected void onPostExecute(Integer version) {
			if (App.getManifestVersionCode() < version) {
				new DownloadTask(context).execute();
			} else {
				App.toast(R.string.last_version, Toast.LENGTH_LONG);
			}
		}
	}

	private class DownloadTask extends AsyncTask<String, Integer, Boolean> {
		private ProgressDialog progressDialog;

		public DownloadTask(Context context) {
			progressDialog = new ProgressDialog(context);
			progressDialog.setMessage(getString(R.string.downloading));
			progressDialog.setCancelable(true);
		}

		@Override
		protected void onPreExecute() {
			progressDialog.show();
		}

		@Override
		protected Boolean doInBackground(String... params) {
			return new Internet().downloadAPK();
		}

		@Override
		protected void onPostExecute(Boolean downloaded) {
			progressDialog.hide();
			if (downloaded) {
				startActivity(App.installationIntent());
			} else {
				App.toast(R.string.download_failed, Toast.LENGTH_LONG);
			}
		}
	}
}